package com.kaihong.template.ble.operation;

import java.util.Optional;
import java.util.function.Consumer;

/**
 * Optional Consumer
 */
public class OptionalConsumer<T> {
    private final Optional<T> optional;

    private OptionalConsumer(Optional<T> optional) {
        this.optional = optional;
    }

    /**
     * Construct an optional consumer object according to optional
     *
     * @param optional Optional
     * @param <T> Optional type
     * @return OptionalConsumer
     */
    public static <T> OptionalConsumer<T> of(Optional<T> optional) {
        return new OptionalConsumer<>(optional);
    }

    /**
     * If the value exists, the consumer is called with that value, otherwise it does nothing.
     *
     * @param consumer consumer
     * @return OptionalConsumer
     */
    public OptionalConsumer<T> ifPresent(Consumer<T> consumer) {
        optional.ifPresent(consumer);
        return this;
    }

    /**
     * If the value does not exist, do nothing, otherwise use the value to call the consumer.
     *
     * @param runnable Runnable
     * @return OptionalConsumer
     */
    public OptionalConsumer<T> ifNotPresent(Runnable runnable) {
        if (runnable != null) {
            if (!optional.isPresent()) {
                runnable.run();
            }
        }
        return this;
    }
}
